<template>
  <div>
    <div class="home-page">

      <div class="banner">
        <div class="container">
          <h1 class="logo-font">conduit</h1>
          <p>A place to share your knowledge.</p>
        </div>
      </div>

      <div class="container page">
        <div class="row">

          <div class="col-md-9">
            <div class="feed-toggle">
              <ul class="nav nav-pills outline-active">
                <li class="nav-item"
                    v-show="!!$store.state.user">
                  <nuxt-link class="nav-link"
                             :class="{
                               active: tab === 'mine'
                             }"
                             exact
                             :to="{
                               name: 'home',
                               query: {
                                 tab: 'mine'
                               }
                             }">Your Feed</nuxt-link>
                </li>
                <li class="nav-item">
                  <nuxt-link class="nav-link"
                             :class="{
                               active: tab === 'all'
                             }"
                             exact
                             :to="{
                               name: 'home',
                               query: {
                                 tab: 'all'
                               }
                             }">Global Feed</nuxt-link>
                </li>
                <li class="nav-item"
                    v-show="!!tag">
                  <nuxt-link class="nav-link"
                             :class="{
                               active: tab === 'tag'
                             }"
                             exact
                             :to="{
                               name: 'home',
                               query: {
                                tab: 'tag',
                                tag: tag
                               }
                             }"># {{tag}}</nuxt-link>
                </li>
              </ul>
            </div>

            <p :style="{
                'margin-top': '10px'
               }"
               v-if="!articles || articles.length === 0">this is no article.</p>
            <article-preview v-for="article in articles"
                             :key="article.slug"
                             :data="article"
                             @favorite="favoriteHandle"></article-preview>

            <nav-page :totalPage="totalPage"
                      :selected="page"
                      :tag="tag"
                      :tab="tab"></nav-page>

          </div>

          <div class="col-md-3">
            <div class="sidebar">
              <p>Popular Tags</p>

              <div class="tag-list">
                <nuxt-link :to="{
                              name: 'home',
                              query: {
                                tab: 'tag',
                                tag
                              }
                           }"
                           class="tag-pill tag-default"
                           v-for="(tag,i) in tags"
                           :key="i">{{ tag }}</nuxt-link>
              </div>
            </div>
          </div>

        </div>
      </div>

    </div>
  </div>
</template>

<script>
import articlePreview from '@/components/articlePreview'
import navPage from '@/components/navPage'
import { getArticles, getFeedArticles, favoriteArticle, unfavoriteArticle } from '@/api/article'
import { getTags } from '@/api/tag'

export default {
  name: 'Home',
  components: {
    articlePreview,
    navPage
  },
  head() {
    return {
      title: 'Home',
      meta: [
        {
          hid: 'home',
          name: 'home',
          content: 'realworld home'
        }
      ]
    }
  },
  async asyncData({ store, query, redirect }) {
    let result = []
    let page = Number(query.page || 1)
    let limit = 20
    let { tag, tab = 'all' } = query
    if ((!store.state.user && tab === 'mine') || (tab === 'tag' && !tag)) {
      return redirect({
        name: 'home'
      })
    }
    let articleFn = tab === 'mine' ? getFeedArticles : getArticles
    try {
      result = await Promise.all([
        articleFn({
          limit,
          offset: (page - 1) * limit,
          tag: tag
        }),
        getTags()
      ])

    } catch (e) {
      // error
      console.log(e.message)
    }
    let {
      articles, articlesCount
    } = result[0].data
    articles.forEach(article => {
      article.favoriteDisable = false
    })
    let {
      tags
    } = result[1].data
    return {
      articles,
      articlesCount,
      tags,
      page,
      limit,
      tag,
      tab
    }
  },
  data() {
    return {
      articles: []
    }
  },
  watchQuery: ['page', 'tag', 'tab'],
  computed: {
    totalPage() {
      return Math.ceil(this.articlesCount / this.limit)
    }
  },
  methods: {
    async favoriteHandle(data) {
      data.favoriteDisable = true
      if (data.favorited) {
        // 已赞，取消赞
        let result = await unfavoriteArticle(data.slug)
        console.log(result)
        data.favorited = false
        data.favoritesCount -= 1
      } else {
        // 点赞
        await favoriteArticle(data.slug)
        data.favorited = true
        data.favoritesCount += 1
      }
      data.favoriteDisable = false
      console.log(data)
    }
  }
}
</script>

<style>
</style>